package com.example.demo.controller;

import com.example.demo.common.JwtUtil;
import com.example.demo.common.Result;
import com.example.demo.jwt.AuthResponse;
import com.example.demo.jwt.LoginRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.util.StringUtils;
import jakarta.validation.Valid;
import com.example.demo.mapper.UserMapper;
import com.example.demo.bean.User;
import org.springframework.security.crypto.password.PasswordEncoder;

import com.example.demo.jwt.ResultCode;
import org.springframework.beans.factory.annotation.Autowired;
/**
 * 认证控制器，处理用户登录等认证相关请求
 *
 * @author Your Name
 * @version 1.0
 */
@RestController
@RequestMapping("/api/auth")
public class AuthController {
    /**
     * 日志记录器
     */
    private static final Logger log = LoggerFactory.getLogger(AuthController.class);

    /**
     * 用户数据访问接口
     */
    private final UserMapper userMapper;

    /**
     * JWT工具类
     */
    private final JwtUtil jwtUtil;

    /**
     * 密码加密器
     */
    private final PasswordEncoder passwordEncoder;

    /**
     * 使用构造器注入
     *
     * @param userMapper 用户数据访问接口
     * @param jwtUtil JWT工具类
     * @param passwordEncoder 密码加密器
     */
    @Autowired
    public AuthController(UserMapper userMapper, JwtUtil jwtUtil, PasswordEncoder passwordEncoder) {
        this.userMapper = userMapper;
        this.jwtUtil = jwtUtil;
        this.passwordEncoder = passwordEncoder;
    }

    /**
     * 用户登录接口
     * 
     * @param request 登录请求，包含用户名和密码
     * @return Result 包含登录结果和token的响应
     */
    @PostMapping("/login")
    public Result<AuthResponse> login(@RequestBody @Valid LoginRequest request) {
        try {
            // 参数验证
            if (!StringUtils.hasText(request.getUsername()) || !StringUtils.hasText(request.getPassword())) {
                log.warn("登录失败：用户名或密码为空");
                return Result.error(ResultCode.VALIDATE_FAILED.getCode(), "用户名和密码不能为空");
            }

            // 从数据库查询用户
            User user = userMapper.findByUsername(request.getUsername());
            if (user == null) {
                log.warn("登录失败：用户 {} 不存在", request.getUsername());
                return Result.error(ResultCode.UNAUTHORIZED.getCode(), "用户名或密码错误");
            }

            // 验证密码
            if (!passwordEncoder.matches(request.getPassword(), user.getUpwd())) {
                log.warn("登录失败：用户 {} 密码错误", request.getUsername());
                return Result.error(ResultCode.UNAUTHORIZED.getCode(), "用户名或密码错误");
            }

            // 生成token - 使用用户信息
            String token = jwtUtil.generateToken(user);
            log.info("用户 {} 登录成功", user.getUname());
            
            // 构建并返回成功响应
            AuthResponse authResponse = new AuthResponse(token, "登录成功");
            return Result.success(authResponse);

        } catch (Exception e) {
            log.error("登录过程发生错误", e);
            return Result.error(ResultCode.ERROR.getCode(), "登录失败：" + e.getMessage());
        }
    }
}